using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;


namespace LenninSoftware.FormEditor.Adapters
{
    class User : BaseControlAdapter
    {
        private SPWeb _web;

        public SPWeb Web
        {
            get { return _web; }
            set { _web = value; }
        }

        public User(SPWeb web)
        {
            _web = web;

        }

        public override Control CreateReadOnlyControl(FieldInfo field)
        {
            Label label = new Label();
            return label;
        }

        public override void LoadReadOnlyData(Control control, SPListItem item, object data)
        {
            Label label = (Label)control;

            if (data == null)
            {
                label.Text = String.Empty;
                return;
            }

            string text = data.ToString();

            string[] items =  text.Split(new string[] {";#"},StringSplitOptions.RemoveEmptyEntries);

            if (items.Length > 0)
                label.Text = items[1];
            else
                label.Text = String.Empty;

            //label.Text = sb.ToString();
        }

        public override System.Web.UI.Control CreateControl(FieldInfo field)
        {
            PeopleSelector peopleEditor = new PeopleSelector();
            peopleEditor.MultiSelect = true;
            peopleEditor.SelectionSet = "User,SPGroup";
            return peopleEditor;
        }

        public override void LoadData(System.Web.UI.Control control, SPListItem item, object data)
        {
            PeopleSelector peopleEditor = (PeopleSelector)control;
            LoadEntityUsers(peopleEditor, (SPFieldUserValueCollection)data);
            ///peopleEditor.RecreateChildControls();
        }

        public override object SaveData(System.Web.UI.Control control, SPListItem item, object currentData)
        {
            PeopleSelector peopleEditor = (PeopleSelector)control;
            return ParseResolvedEntities(Web, peopleEditor.ResolvedEntities);
        }

        public override void Reset(System.Web.UI.Control control)
        {
            PeopleSelector peopleEditor = (PeopleSelector)control;
            peopleEditor.ResolvedEntities.Clear();
            peopleEditor.Entities.Clear();
        }

        private SPFieldUserValueCollection ParseResolvedEntities(SPWeb web, System.Collections.ArrayList resolvedEntities)
        {
            SPFieldUserValueCollection result = new SPFieldUserValueCollection();


            foreach (PickerEntity entity in resolvedEntities)
            {
                switch ((string)entity.EntityData["PrincipalType"])
                {
                    case "User":

                        if (entity.EntityData.ContainsKey("SPUserID"))
                        {
                            int userID = int.Parse((string)entity.EntityData["SPUserID"]);
                            result.Add(new SPFieldUserValue(web, userID, entity.Key));
                        }
                        else
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                                {
                                    try
                                    {
                                        string displayName = (string)entity.EntityData["DisplayName"];
                                        web.AllUsers.Add(entity.Key, String.Empty, displayName, String.Empty);

                                        SPUser user = web.AllUsers[entity.Key];
                                        result.Add(new SPFieldUserValue(web, user.ID, entity.Key));
                                    }
                                    catch (Exception)
                                    {

                                    }
                                });
                        

                        break;

                    case "SharePointGroup":

                        if (entity.EntityData.ContainsKey("SPGroupID"))
                        {
                            int groupID = int.Parse((string)entity.EntityData["SPGroupID"]);
                            result.Add(new SPFieldUserValue(web, groupID, entity.Key));
                        }
                        break;
                }
            }

            return result;

        }

        private void LoadEntityUsers(PeopleEditor peoplePicker, SPFieldUserValueCollection users)
        {
            ArrayList entities = new  ArrayList();
            foreach (SPFieldUserValue userValue in users)
            {
                PickerEntity entity = new PickerEntity();
                entity.Key = userValue.LookupValue;
                entity = peoplePicker.ValidateEntity(entity);
                entities.Add(entity);
                //peoplePicker.Entities.Add(entity);
            }

            peoplePicker.UpdateEntities(entities);
        }

        public override bool isEmpty(Control control)
        {
            PeopleEditor peopleEditor = (PeopleEditor)control;
            return peopleEditor.ResolvedEntities.Count == 0;
        }
    }
}
